/*
 * DEPRECATED
 * http://code.google.com/apis/ajaxsearch/documentation/
 * http://code.google.com/apis/base/docs/2.0/attrs-queries.html
 *
 * NEW API
 * http://code.google.com/apis/shopping/search/
 */

var tgd = tgd || {};
tgd.Services = tgd.Services || {};
tgd.Services.Google = tgd.Services.Google || {};
tgd.Services.Google.Search = tgd.Services.Google.Search || {};



/*
 * Static method that asynchronously requests data from Google.
 * Once data is returned, it will be processed and sent to the callback specified by the client (onResultsReturned).
 */
tgd.Services.Google.Search.getUPC = function(upc) {
	if (tgd.Services.Google.Search.onResultsReturned === undefined) {
		throw new Error("onResultsReturned was not overridden by client.");
	}

	var attributesElement = document.createElement("script");
	attributesElement.setAttribute("id", "attributes");
	attributesElement.setAttribute("src", "http://www.google.com/base/feeds/snippets/-/products/?bq=" + upc + "[upc]&alt=json-in-script&callback=tgd.Services.Google.Search.Callback&max-results=10&crowdby=title:1&key=ABQIAAAAKki0ect4eswzmpY3Kr_M5xRkTzXQYuYbuH6E0wOmuVw3dUbkhxSTBv2_y3ZiXiQu_pYQK7P2d5OgDw");
	attributesElement.setAttribute("type", "text/javascript");
	document.documentElement.firstChild.appendChild(attributesElement);
}

//Static method for callback from Google.
// { UPC, Title : [ { Name, Source } ], Thumb : [ { URL, Source } ], Raw : [] }
// Title array is assumed sorted (see implementation)
tgd.Services.Google.Search.Callback = function (json) {
	var result = {};
	result.UPC = json.feed.title.$t.match(/\d+/)[0];  //todo: do some error handling
	result.Title = [];
	result.Thumb = [];

	if (json.feed.entry) {
	    result.Raw = json.feed.entry; 

		for (var i = 0; i < json.feed.entry.length; ++i) {
			result.Title.push( { Name : json.feed.entry[i].title.$t, Source : json.feed.entry[i].author[0].name.$t } );
			if (json.feed.entry[i].g$image_link) {  //todo: should i be checking if array length === 1? or just exists?
				result.Thumb.push( { URL : json.feed.entry[i].g$image_link[0].$t, Source : json.feed.entry[i].author[0].name.$t } );
			}
		}
	}

    result.Title = result.Title.sort(function(a, b) { if (a.Name.toUpperCase() < b.Name.toUpperCase()) { return -1; } else if (a.Name.toUpperCase() > b.Name.toUpperCase()) { return 1; } else { return 0 } } )

	tgd.Services.Google.Search.onResultsReturned(result);
}

//Static method that must be overridden by client.
//tgd.Services.Google.Search.onResultsReturned = function() {};
